package yuan.deng.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//jdbc工具类
public class JDBCUtlis {
    //构造方法私有化
    private JDBCUtlis(){}

    //声明配置变量
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //提供静态代码块读取配置文件，静态代码块可以在类一加载就加载配置文件的内容，给参数赋值
    static {
        try {
            InputStream is = JDBCUtlis.class.getClassLoader().getResourceAsStream("config.properties");//读取配置文件输入流
            Properties pro=new Properties();
            pro.load(is);//加载流内容
            driver = pro.getProperty("driverClass");//获取流内容给对象赋值
            url = pro.getProperty("url");
            username = pro.getProperty("username");
            password = pro.getProperty("password");
            Class.forName(driver);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取连接的方法
    public static Connection getConn(){
        Connection connection=null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    //释放资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if(connection!=null){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

        if(statement!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //释放资源
    public static void close(Connection connection, Statement statement){
        JDBCUtlis.close(connection,statement,null);
    }
}
